package com.jinlejia.erp.ui.customer;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.base.VisitorApiConfig;
import com.jinlejia.erp.databinding.ActivityDetailCustomerBinding;
import com.jinlejia.erp.ui.common.GuideDialog;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.ui.common.SheetSelect;
import com.jinlejia.erp.ui.common.SheetSelect2;
import com.jinlejia.erp.ui.home.VisitScheduleActivity;
import com.jinlejia.erp.ui.house.InterestHouseActivity;
import com.jinlejia.erp.ui.new_house.recommend.RecommendClientsActivity;
import com.jinlejia.erp.utils.ACache;
import com.jinlejia.erp.utils.ActivityCollector;
import com.jinlejia.erp.utils.CallUtils;
import com.jinlejia.erp.utils.DataFilter;
import com.nimlib.NimChartP2PActivity;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 客源详情
 */
public class DetailCustomerActivity extends FragmentActivity {

    private String csCode;
    private String type;
    private String sex;
    private boolean isAttention = false;
    private JSONObject customerData;
    ArrayList<Map<String, Object>> phoneList = new ArrayList<>();
    private String phoneNO;
    private ProgressDialog progressDialog;

    private ActivityDetailCustomerBinding binding;

    //CustomerHideDialog 对话框使用，如果已经关联的话，就显示解除关联按钮
    private boolean isGL = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_detail_customer);
        binding.setEvent(this);
        EventBus.getDefault().register(this);
        progressDialog = new ProgressDialog(this, "加载中...");
        progressDialog.show();
        csCode = getIntent().getStringExtra("csCode");
        type = getIntent().getStringExtra("type");
        sex = getIntent().getStringExtra("sex");
        if (getIntent().hasExtra("daikan")){
            if (null != progressDialog && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
            ActivityCollector.finishAll2();
            binding.segmentControl.setSelectedIndex(1);
            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            ft.replace(R.id.content, LookAtFragment.newInstance(csCode, type));
            ft.commitAllowingStateLoss();
        }else{
            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            ft.replace(R.id.content, DetailCustomerFragment.newInstance(csCode, type));
            ft.commitAllowingStateLoss();
        }
        binding.segmentControl.setOnSegmentControlClickListener(index -> {
            FragmentManager fm1 = getSupportFragmentManager();
            FragmentTransaction ft1 = fm1.beginTransaction();
            switch (index) {
                case 0:
                    // 详情
                    ft1.replace(R.id.content, DetailCustomerFragment.newInstance(csCode, type));
                    ft1.commitAllowingStateLoss();
                    break;
                case 1:
                    //带看
                    ft1.replace(R.id.content, LookAtFragment.newInstance(csCode, type));
                    ft1.commitAllowingStateLoss();
                    break;
                case 2:
                    //约看
                    ft1.replace(R.id.content, AppointmentFragment.newInstance(csCode, type, sex));
                    ft1.commitAllowingStateLoss();
                    break;
                default:
                    break;
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        //指引弹出层
        if (TextUtils.isEmpty(ACache.get(this).getAsString("customers_detail"))) {
            GuideDialog dialog = new GuideDialog(this, "customers_detail", R.mipmap.guide_customers_detail);
            dialog.setDissmissListener(() -> {
                if (TextUtils.isEmpty(ACache.get(DetailCustomerActivity.this).getAsString("customers_detail_type")))
                    new GuideDialog(DetailCustomerActivity.this, "customers_detail_type", R.mipmap.guide_customer_details_type).show();
            });
        }

    }

    private CustomerHideDialog hideDialog;
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.bt_add:
                if (hideDialog==null){
                    hideDialog = new CustomerHideDialog(this);
                }
                hideDialog.setGL(isGL);
                hideDialog.setAttention(isAttention);
                hideDialog.setCancelable(false);
                hideDialog.show();
                hideDialog.getfloower().setOnClickListener(view1 -> {
                    //收藏
                    if (isAttention) {
                        removeAttention();
                    } else {
                        saveAttention();
                    }
                    hideDialogDismiss();
                });//收藏
                hideDialog.getwriteFollow().setOnClickListener(view12 -> {
                    hideDialogDismiss();
                    //写跟进
                    Intent intent = new Intent(DetailCustomerActivity.this, WriteCustomerFollowActivity.class);
                    intent.putExtra("code", csCode);
                    intent.putExtra("type", type);
                    startActivity(intent);

                });//跟进
                hideDialog.getInterest().setOnClickListener(view13 -> {
                    hideDialogDismiss();
                    //兴趣
                    Intent interestIntent = new Intent(DetailCustomerActivity.this, InterestHouseActivity.class);
                    interestIntent.putExtra("type", type);
                    interestIntent.putExtra("csCode", csCode);
                    startActivity(interestIntent);

                });//兴趣
                hideDialog.getoldHouse().setOnClickListener(view14 -> {
                    hideDialogDismiss();
                    //带看
                    ArrayList<String> cList = new ArrayList<>();
                    cList.add("二手房带看");
                    cList.add("二手房约看");
                    SheetSelect2 sheetSelect = new SheetSelect2(DetailCustomerActivity.this, "请选择", cList);
                    sheetSelect.show();
                    sheetSelect.setOnSelectListener(new SheetSelect2.OnSelectListener() {
                        @Override
                        public void select(Object o) {
                            if (o.equals("二手房带看")) {
                                validateVisit();
                            } else {
                                validateAbout();
                            }
                        }
                    });
                });//二手房带看
                hideDialog.getnewHouse().setOnClickListener(view15 -> {
                    hideDialogDismiss();
                    //新房报备
                    Intent intent1 = new Intent(DetailCustomerActivity.this, RecommendClientsActivity.class);
                    intent1.putExtra("csCode", csCode);
                    intent1.putExtra("phone", phoneNO);
                    intent1.putExtra("cNmae", getIntent().getStringExtra("name"));
                    startActivity(intent1);
                });//新房报备
                hideDialog.getupdateData().setOnClickListener(view16 -> {
                    hideDialogDismiss();
                    //编辑
                    validateEdit();
                });//修改资料
                hideDialog.getclearBinding().setOnClickListener(view17 -> {
                    clearBindingVisitor();
                });
                break;
            case R.id.contact_customer:
                //联系客户
                if (phoneList.size() == 0) {
                    CallUtils.CallTel(DetailCustomerActivity.this, phoneNO);
                } else {
                    ArrayList<Map<String, Object>> cList = new ArrayList<>();
                    for (int i = 0; i < phoneList.size(); i++) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("tel", phoneList.get(i).get("tel"));
                        if (phoneList.get(i).get("contactType").toString().equals("1")) {
                            map.put("name", "手机");
                        } else if (phoneList.get(i).get("contactType").toString().equals("2")) {
                            map.put("name", "办公");
                        } else if (phoneList.get(i).get("contactType").toString().equals("3")) {
                            map.put("name", "住宅");
                        }
                        cList.add(map);
                    }
                    SheetSelect sheetSelect = new SheetSelect(DetailCustomerActivity.this, "选择联系方式", cList);
                    sheetSelect.show();
                    sheetSelect.setOnSelectListener(o -> {
                        Map<String, Object> map = (Map<String, Object>) o;
                        phoneNO = map.get("tel").toString();
                        CallUtils.CallTel(DetailCustomerActivity.this, phoneNO);
                    });
                }
                break;
            case R.id.tvBtSednMessage:
                NimChartP2PActivity.start(this, this.openId);
                break;
            default:
                break;
        }
    }

    private String openId = null;

    private void hideDialogDismiss(){
        if (hideDialog!=null)
            hideDialog.dismiss();
        hideDialog = null;
    }
    @Subscriber(tag = "TAG_CUSTOMER_DATA")
    private void customerData(JSONObject data) {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        customerData = data;
        if (data.getIntValue("isAttention") == 0) {
            isAttention = false;
        } else {
            isAttention = true;
        }
        //联系方式
        if (data.containsKey("customerContactTypeList"))
            phoneList = JSON.parseObject(data.get("customerContactTypeList").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
            });
        phoneNO = data.get("tel").toString();
    }

    //如果获取到微信ID，则显示发消息按钮
    @Subscriber(tag = "TAG_VISITOR_DATA")
    private void visitor(JSONObject obj) {
        String openId = obj.getString("openId");
        String state = obj.getString("state"); //用户关联状态 YES:已关联 其他：未关联
        if (TextUtils.isEmpty(openId)){
            binding.tvBtSednMessage.setVisibility(View.GONE);
            this.openId = openId;
        }else {
            binding.tvBtSednMessage.setVisibility(View.VISIBLE);
            this.openId = openId;
        }
        if ("YES".equals(state)){ //用户已关联
            isGL = true;
        }else {
            isGL = false;
        }
    }


    public void saveAttention() {
        String url = "";
        JSONObject object = new JSONObject();
        object.put("resourceCode", csCode);
        if (type.equals("sale")) {
            object.put("attentionServiceType", 1);
            url = ApiConfig.SHS_CUSTOMER_ATTENTION;
        } else {
            object.put("attentionServiceType", 0);
            url = ApiConfig.RENT_CUSTOMER_ATTENTION;
        }
        OkHttpUtils.postString()
                .url(url)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(object.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(DetailCustomerActivity.this, response)) {
                            isAttention = true;
                            // binding.btCollect.setImageResource(R.mipmap.ic_has_collect);
                            CustomToast.showToast(DetailCustomerActivity.this, "关注成功", 1500);
                        } else {
                            isAttention = false;
                            //binding.btCollect.setImageResource(R.mipmap.ic_collect);
                        }
                    }
                });
    }

    public void removeAttention() {
        String url = "";
        if (type.equals("sale")) {
            url = ApiConfig.SHS_CUSTOMER_REMOVE_ATTENTION;
        } else {
            url = ApiConfig.RENT_CUSTOMER_REMOVE_ATTENTION;
        }
        JSONObject object = new JSONObject();
        object.put("resourceCode", csCode);
        OkHttpUtils.postString()
                .url(url)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(object.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(DetailCustomerActivity.this, response)) {
                            isAttention = false;
                            //binding.btCollect.setImageResource(R.mipmap.ic_collect);
                            CustomToast.showToast(DetailCustomerActivity.this, "取消成功", 1500);
                        } else {
                            isAttention = true;
                            //binding.btCollect.setImageResource(R.mipmap.ic_has_collect);
                        }
                    }
                });
    }

    private void validateEdit() {
        String url;
        JSONObject object = new JSONObject();
        object.put("csCode", csCode);
        if (type.equals("sale")) {
            object.put("type", "1");
            url = ApiConfig.VALIDATE_EDIT_CUSTOMER;
        } else {
            url = ApiConfig.VALIDATE_RENT_EDIT_CUSTOMER;
            object.put("type", "0");
        }
        OkHttpUtils.postString()
                .url(url)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(object.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(DetailCustomerActivity.this, response)) {
                            hideDialogDismiss();
                            EventBus.getDefault().postSticky(customerData, "TAG_EDIT_CUSTOMER");
                            Intent intent = new Intent(DetailCustomerActivity.this, RecordCustomer1Activity.class);
                            intent.putExtra("type", type);
                            startActivity(intent);
                        }
                    }
                });
    }

    private void validateVisit() {
        JSONObject object = new JSONObject();
        object.put("csCode", csCode);
        if (type.equals("sale")) {
            object.put("type", "1");
        } else {
            object.put("type", "0");
        }
        OkHttpUtils.postString()
                .url(ApiConfig.SAVE_VISIT_VALIDATE)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(object.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(DetailCustomerActivity.this, response)) {
                            hideDialogDismiss();
                            ActivityCollector.addActivity2(DetailCustomerActivity.this);
                            Intent intent1 = new Intent(DetailCustomerActivity.this, EnteringVisitActivity1.class);
                            intent1.putExtra("csCode", csCode);
                            intent1.putExtra("type", type);
                            intent1.putExtra("sex", getIntent().getStringExtra("sex"));
                            intent1.putExtra("name", getIntent().getStringExtra("name"));
                            startActivity(intent1);
                        }
                    }
                });
    }

    /**
     * 录约看验证
     */
    private void validateAbout() {
        JSONObject object = new JSONObject();
        object.put("csCode", csCode);
        if (type.equals("sale")) {
            object.put("type", "1");
        } else {
            object.put("type", "0");
        }
        OkHttpUtils.postString()
                .url(ApiConfig.CUSTOMER_VALIDATE_APPOINTMENT)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(object.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(DetailCustomerActivity.this, response)) {
                            Intent intent2 = new Intent(DetailCustomerActivity.this, VisitScheduleActivity.class);
                            intent2.putExtra("property", "Input");
                            intent2.putExtra("type", type);
                            intent2.putExtra("sex", getIntent().getStringExtra("sex"));
                            intent2.putExtra("csCode", getIntent().getStringExtra("csCode"));
                            intent2.putExtra("customerName", getIntent().getStringExtra("name"));
                            startActivity(intent2);
                        }
                    }
                });
    }
    //解除关联访客
    private void clearBindingVisitor() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("csCode", csCode);
        OkHttpUtils.postString()
                .url(VisitorApiConfig.CLEARBINDINGVISITOR)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        CustomToast.showToast(DetailCustomerActivity.this, "网络错误", 1500);
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(DetailCustomerActivity.this, response)) {
                            EventBus.getDefault().post("REFRESH","TAG_REFRESH_CUSTOME");
                            CustomToast.showToast(DetailCustomerActivity.this, "解除关联成功", 1500);
                            hideDialogDismiss();
                        }
                    }
                });

    }

    @Override
    protected void onDestroy() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        super.onDestroy();
    }
}
